<?php

class SJB_Classifieds_MyListings extends SJB_Function
{
	public function isAccessible()
	{
		if ($this->getAclRoleID())
			$this->setPermissionLabel(array('subuser_add_listings', 'subuser_manage_listings'));
		return parent::isAccessible();
	}

	public function execute()
	{
		if (!function_exists('_filter_data')) {
			function _filter_data(&$array, $key, $pattern)
			{
				if (isset($array[$key])) {
					if (!preg_match($pattern, $array[$key]))
						unset($array[$key]);
				}
			}
		}

		_filter_data($_REQUEST, 'sorting_field', "/^[_\w\d]+$/");
		_filter_data($_REQUEST, 'sorting_order', "/(^DESC$)|(^ASC$)/i");
		_filter_data($_REQUEST, 'default_sorting_field', "/^[_\w\d]+$/");
		_filter_data($_REQUEST, 'default_sorting_order', "/(^DESC$)|(^ASC$)/i");

		$tp = SJB_System::getTemplateProcessor();
		if (!SJB_UserManager::isUserLoggedIn()) {
			$errors['NOT_LOGGED_IN'] = true;
			$tp->assign("ERRORS", $errors);
			$tp->display("error.tpl");
			return;
		}

		$currentUser = SJB_UserManager::getCurrentUser();
		$current_user_sid = $currentUser->getSID();

		$listing_type_id = isset($_REQUEST['listing_type_id']) ? $_REQUEST['listing_type_id'] : null;
		$listing_type_sid = !empty($listing_type_id) ? SJB_ListingTypeManager::getListingTypeSIDByID($listing_type_id) : 0;
		$acl = SJB_Acl::getInstance();

		$my_listings_criteria = array('user_sid' => array('equal' => $current_user_sid));
		if ($currentUser->isSubuser()) {
			$subuserInfo = $currentUser->getSubuserInfo();
			if (!$acl->isAllowed('subuser_manage_listings', $subuserInfo['sid']))
				$my_listings_criteria['subuser_sid'] = array('equal' => $subuserInfo['sid']);
		}
		
		SJB_ListingManager::deletePreviewListingsByUserSID($current_user_sid);

		$searcher = new SJB_ListingSearcher();

		// to save criteria in the session different from search_results
		$criteria_saver = new SJB_ListingCriteriaSaver('MyListings');

		if (isset($_REQUEST['restore']))
			$_REQUEST = array_merge($_REQUEST, $criteria_saver->getCriteria());

		$listing = new SJB_Listing(array(), $listing_type_sid);
		$id_alias_info = $listing->addIDProperty();
		$listing->addActivationDateProperty();
		$listing->addKeywordsProperty();
		$listing->addPicturesProperty();
		$listing_type_id_alias_info = $listing->addListingTypeIDProperty();

		$criteria = SJB_SearchFormBuilder::extractCriteriaFromRequestData($_REQUEST + $my_listings_criteria, $listing);

		$aliases = new SJB_PropertyAliases();
		$aliases->addAlias($id_alias_info);
		$aliases->addAlias($listing_type_id_alias_info);

		if (isset($_REQUEST['listings'])) {
			$listings_ids = $_REQUEST['listings'];
			if (isset($_REQUEST['action_deactivate'])) {
				foreach ($listings_ids as $listing_id => $value)
					SJB_ListingManager::deactivateListingBySID($listing_id);
			}
			elseif (isset($_REQUEST['action_activate'])) {
				$payment_amount = 0;
				$listings_ids_arr = array();
				foreach ($listings_ids as $listing_id => $value) {
					$listingInfo = SJB_ListingManager::getListingInfoBySID($listing_id);
					$productInfo = !empty($listingInfo['product_info']) ? unserialize($listingInfo['product_info']) : array();
					if (SJB_ListingManager::getIfListingHasExpiredBySID($listing_id) && isset($productInfo['renewal_price']) && $productInfo['renewal_price'] > 0) {
						$payment_amount += $productInfo['renewal_price'];
						$listings_ids_arr[] = $listing_id;
					}
					else {
						SJB_ListingManager::activateListingBySID($listing_id);
					}
				}
				if (!empty($listings_ids_arr)) {
					$user_sid = $current_user_sid;
					$items['products'][1]  = '-1';
					$subTotalPrice = $payment_amount;
					$items['price'][1] = sprintf('%.02f', $subTotalPrice);
					$items['amount'][1] = sprintf('%.02f', $subTotalPrice);
					$items['custom_item'][1] = "Payment for listing(s) #: ". implode(',', $listings_ids_arr);
					$items['custom_info'][1] =  array('listings_id' => $listings_ids_arr, 'type' => 'activateListing');
					$items['qty'][1] = '1';
					$tax_info = SJB_TaxesManager::getTaxInfoByUserSidAndPrice($user_sid, $subTotalPrice);
					$totalPrice = SJB_InvoiceManager::getTotalPrice($subTotalPrice, $tax_info['tax_amount'], $tax_info['price_includes_tax']);
					$invoice_info = array(
						'user_sid' => $user_sid,
						'include_tax' => !empty($tax_info['tax_info']['tax_name']) ? 1 : 0,
						'total' => $totalPrice,
						'sub_total' => $subTotalPrice,
						'success_page_url' => SJB_System::getSystemSettings('SITE_URL') . "/activate-listing/",
						'status' => SJB_Invoice::INVOICE_STATUS_UNPAID,
						'tax_info' => $tax_info,
						'items' => $items,
						'is_recurring' => false
					);
					$invoice_sid = SJB_InvoiceManager::generateInvoice($invoice_info);
					$page = SJB_Request::getVar('page', false);
					if ($page)
						$page = '&page=' . $page;
					$payment_page_url = SJB_System::getSystemSettings('SITE_URL') . "/payment-page/?invoice_sid=" . $invoice_sid . $page;
					SJB_HelperFunctions::redirect($payment_page_url);
					return;
				}
			}
			else {
				if (isset($_REQUEST['action_delete'])) {
					$found_listings_sids = $criteria_saver->getObjectSIDs();
					foreach ($listings_ids as $listing_id => $value) {
						SJB_ListingManager::deleteListingBySID($listing_id);
						$i = array_search($listing_id, $found_listings_sids);
						unset($found_listings_sids[$i]);
					}
					$criteria_saver->setSessionForObjectSIDs($found_listings_sids);

				}
				else if (isset($_REQUEST['action_sendToApprove'])) {
					foreach ($listings_ids as $listing_id => $value)
						SJB_ListingManager::setListingApprovalStatus($listing_id, 'pending');
				}
			}
			SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/my-listings/');
		}

		// получим информацию о имеющихся листингах
		$listingsInfo = array();
		$currentUserInfo = SJB_UserManager::getCurrentUserInfo();
		$userGroupID = SJB_UserGroupManager::getUserGroupIDBySID($currentUserInfo['user_group_sid']);

		switch ($userGroupID) {
			case 'JobSeeker':
				$listingTypeID = 'Resume';
				break;
			default:
				$listingTypeID = 'Job';
				break;
		}
		$contractInfo['extra_info']['listing_amount'] = 0;

		if ($acl->isAllowed('post_' . $listingTypeID)) {
			$permissionParam = $acl->getPermissionParams('post_' . $listingTypeID);
			if (empty($permissionParam))
				$contractInfo['extra_info']['listing_amount'] = 'unlimited';
			else
				$contractInfo['extra_info']['listing_amount'] = $permissionParam;
		}
		$currentUser = SJB_UserManager::getCurrentUser();
		$contractsSIDs = $currentUser->getContractID();
		$listingsInfo['listingsNum'] = SJB_ContractManager::getListingsNumberByContractSIDsListingType($contractsSIDs, $listingTypeID);
		$listingsInfo['listingsMax'] = $contractInfo['extra_info']['listing_amount'];
		if ($listingsInfo['listingsMax'] === 'unlimited')
			$listingsInfo['listingsLeft'] = 'unlimited';
		else {
			$listingsInfo['listingsLeft'] = $listingsInfo['listingsMax'] - $listingsInfo['listingsNum'];
			$listingsInfo['listingsLeft'] = $listingsInfo['listingsLeft'] < 0 ? 0 : $listingsInfo['listingsLeft'];
		}

		$userListingsSID = SJB_ListingDBManager::getListingsSIDByUserSID($currentUserInfo['sid'], false, 1);

		$listingsInfoBySID = '';
		if (!empty($userListingsSID)) {
			$listingsInfoBySID = SJB_ListingManager::getListingInfoBySID($userListingsSID[0]);
			$listingsInfo['listingsType'] = SJB_ListingTypeManager::getListingTypeIDBySID($listingsInfoBySID['listing_type_sid']);
		}

		$tp->assign('listingsInfo', $listingsInfo);

		$search_form_builder = new SJB_SearchFormBuilder($listing);
		$search_form_builder->registerTags($tp);
		$search_form_builder->setCriteria($criteria);

		$tp->display('my_listings_form.tpl');
		$page = SJB_Request::getVar("page", 1);

		$sorting_field = SJB_Request::getVar("sorting_field", false);
		$sorting_order = SJB_Request::getVar("sorting_order", false);

		if ($sorting_order && $sorting_order) { //save order info in the session
			$criteria_saver->setSessionForOrderInfo(array
			(
				'sorting_field' => $sorting_field,
				'sorting_order' => $sorting_order,
			));
		}

		$found_listings_sids = $searcher->getObjectsSIDsByCriteria($criteria, $aliases); // get found listing sids
		$order_info = $criteria_saver->getOrderInfo(); //save order info in the session

		if (empty($order_info)) {
			$order_info['sorting_field'] = $sorting_field ? $sorting_field : !empty($_REQUEST['default_sorting_field']) ? $_REQUEST['default_sorting_field'] : 'activation_date';
			$order_info['sorting_order'] = !empty($_REQUEST['default_sorting_order']) ? $_REQUEST['default_sorting_order'] : 'DESC';

			$criteria_saver->setSessionForOrderInfo(array
			(
				'sorting_field' => $order_info['sorting_field'],
				'sorting_order' => $order_info['sorting_order'],
			));
		}
		// save values in the REQUEST to initiate sorting below
		$_REQUEST['sorting_field'] = $order_info['sorting_field'];
		$_REQUEST['sorting_order'] = $order_info['sorting_order'];

		$listings_per_page = $criteria_saver->getListingsPerPage(); //save 'listings per page' in the session
		if (empty($listings_per_page))
			$listings_per_page = 10;
		$listings_per_page = SJB_Request::getVar("listings_per_page", $listings_per_page);
		$criteria_saver->setSessionForListingsPerPage($listings_per_page);
		$criteria_saver->setSessionForCurrentPage($page);
		$criteria_saver->setSessionForCriteria($_REQUEST);

		// get Applications
		$appsGroups = SJB_Applications::getAppGroupsByEmployer($currentUserInfo['sid']);
		$apps = array();
		foreach ($appsGroups as $group) {
			$apps[$group['listing_id']] = $group['count'];
		}

		$criteria_saver->setSessionForObjectSIDs($found_listings_sids);
		$search_criteria_structure = $criteria_saver->createTemplateStructureForCriteria();
		$listing_search_structure = $criteria_saver->createTemplateStructureForSearch();

		/**************** S O R T I N G *****************/
		$empty_listing = new SJB_Listing(array(), $listing_type_sid);
		$empty_listing->addPicturesProperty();
		$empty_listing->addIDProperty();
		$empty_listing->addListingTypeIDProperty();
		$empty_listing->addActivationDateProperty();
		$empty_listing->addNumberOfViewsProperty();
		$empty_listing->addApplicationsProperty();
		$empty_listing->addSubuserProperty();
		$empty_listing->addActiveProperty();
		$empty_listing->addExpirationDateProperty(null);
		$sorted_found_listings_sids = array();

		if (!empty($found_listings_sids) && isset($_REQUEST['sorting_field'], $_REQUEST['sorting_order']) &&
				$empty_listing->propertyIsSet($_REQUEST['sorting_field'])
		) {
			$property = $empty_listing->getProperty($listing_search_structure['sorting_field']);

			$sorting_field = $_REQUEST['sorting_field'];
			$sorting_order = $_REQUEST['sorting_order'];
			$ids = join(", ", $found_listings_sids);
			switch ($sorting_field)
			{
				case 'listing_type':
					$sql = '	SELECT listings.*
								FROM listings
									LEFT JOIN listing_types on listings.listing_type_sid = listing_types.sid
								WHERE listings.sid IN (' . $ids . ')
								ORDER BY listing_types.id ' . $sorting_order;
					break;

				case 'id':
					$sql = '	SELECT listings.*
								FROM listings
								WHERE listings.sid IN (' . $ids . ')
								ORDER BY sid ' . $sorting_order;
					break;

				case 'subuser_sid':
					$sql = '	SELECT `l`.*
								FROM listings `l`
									INNER JOIN `users` `u` ON (`l`.`subuser_sid` <> 0 AND `l`.`subuser_sid` = `u`.`sid`) OR (`l`.`subuser_sid` = 0 AND `l`.`user_sid` = `u`.`sid`)
								WHERE `l`.sid IN (' . $ids . ')
								ORDER BY `u`.`username` ' . $sorting_order;
					break;

				case 'applications':
					$sql = 'SELECT listings.sid, count(apps.id) as appCount
							FROM listings
								LEFT JOIN applications as apps ON listings.sid = apps.listing_id
							WHERE listings.sid IN (' . $ids . ')
							GROUP BY listings.sid
							ORDER BY appCount ' . $sorting_order;
					break;

				default:
					$listing_request_creator = new SJB_ListingRequestCreator($found_listings_sids, array('property' => $property,
										'sorting_order' => $listing_search_structure['sorting_order']));
					$sql = $listing_request_creator->getRequest();
					break;
			}

			$cache = SJB_Cache::getInstance();
			$cacheId = md5($sql);
			if ($cache->test($cacheId)) {
				$listings_info = $cache->load($cacheId);
			}
			else {
				$listings_info = SJB_DB::query($sql);
				$cache->save($listings_info, $cacheId, array(SJB_Cache::TAG_LISTINGS));
			}

			$listings_sids = array();
			foreach ($listings_info as $listing_info)
				$listings_sids[$listing_info['sid']] = $listing_info['sid'];

			$sorted_found_listings_sids = array_keys($listings_sids);
		}
		else {
			$sorted_found_listings_sids = $found_listings_sids;
		}
		$criteria_saver->setSessionForObjectSIDs($sorted_found_listings_sids);

		$sortable_properties = array();
		$property_list = $empty_listing->getPropertyList();

		foreach ($property_list as $property)
			$sortable_properties[$property]['is_sortable'] = true;

		/**************** P A G I N G *****************/
		if ($listing_search_structure['current_page'] > $listing_search_structure['pages_number'])
			$listing_search_structure['current_page'] = $listing_search_structure['pages_number'];
		if ($listing_search_structure['current_page'] < 1)
			$listing_search_structure['current_page'] = 1;

		$sorted_found_listings_sids_by_pages = array_chunk($sorted_found_listings_sids, $listing_search_structure['listings_per_page'], true);

		/************* S T R U C T U R E **************/
		$listings_structure = array();
		$listing_structure_meta_data = array();

		if (isset($sorted_found_listings_sids_by_pages[$listing_search_structure['current_page'] - 1])) {
			foreach ($sorted_found_listings_sids_by_pages[$listing_search_structure['current_page'] - 1] as $sid) {
				$listing = SJB_ListingManager::getObjectBySID($sid);
				$listing->addPicturesProperty();
				$listing_structure = SJB_ListingManager::createTemplateStructureForListing($listing);
				$listings_structure[$listing->getID()] = $listing_structure;

				if (isset($listing_structure['METADATA']))
					$listing_structure_meta_data = array_merge($listing_structure_meta_data, $listing_structure['METADATA']);
			}
		}

		/*************** D I S P L A Y ****************/
		$metaDataProvider = SJB_ObjectMother::getMetaDataProvider();
		$metadata = array();
		$metadata["listing"] = $metaDataProvider->getMetaData($listing_structure_meta_data);

		$waitApprove = false;
		if (!empty($listingsInfoBySID))
			$waitApprove = SJB_ListingTypeManager::getWaitApproveSettingByListingType($listingsInfoBySID['listing_type_sid']);

		$tp->assign('show_rates', SJB_Settings::getSettingByName('show_rates'));
		$tp->assign('show_comments', SJB_Settings::getSettingByName('show_comments'));
		$tp->assign("METADATA", $metadata);
		$tp->assign("sorting_field", $listing_search_structure['sorting_field']);
		$tp->assign("sorting_order", $listing_search_structure['sorting_order']);
		$tp->assign("property", $sortable_properties);
		$tp->assign("listing_search", $listing_search_structure);
		$tp->assign("search_criteria", $search_criteria_structure);
		$tp->assign("listings", $listings_structure);
		$tp->assign("waitApprove", $waitApprove);
		$tp->assign("apps", $apps);

		$hasSubusersWithListings = false;
		$subusers = SJB_UserManager::getSubusers($currentUserInfo['sid']);
		foreach ($subusers as $subuser) {
			if ($acl->isAllowed('subuser_add_listings', $subuser['sid']) || $acl->isAllowed('subuser_manage_listings', $subuser['sid'])) {
				$hasSubusersWithListings = true;
				break;
			}
		}
		$tp->assign('hasSubusersWithListings', $hasSubusersWithListings);

		$tp->display('my_listings.tpl');
	}
}